package org.comet.auxiliary.client.liaobei.util;

import org.comet.auxiliary.common.util.StringUtil;
import org.comet.auxiliary.common.util.config.ClientConfigHelper;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author wq
 * @date 2019-11-13
 * @description ping net state
 */
public class NetStateUtil {

    public static boolean isConnect() {
        Runtime runtime = Runtime.getRuntime();
        try {
            String ip = (String) ClientConfigHelper.getConfig().get("ip");
            if (StringUtil.isBlank(ip)) {
                ip = "google.cn";
            }
            Process process = runtime.exec("ping " + ip);
            InputStream is = process.getInputStream();
            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line;
            int i = 0;
            boolean flag = false;
            while ((line = br.readLine()) != null) {
                if (!StringUtil.isBlank(line) && i++ > 0) {
                    flag = line.contains("TTL") || line.contains("ttl");
                    break;
                }
            }
            is.close();
            isr.close();
            br.close();
            process.destroy();
            return flag;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
}